<template>
  <div style="display: flex;justify-content: space-evenly">
    <div class="main-body" style="display: block">
      <div style="display: block; padding: 20px;padding-left: 0px">
        <div style="display: flex;justify-content: start; font-size: 20px">
          新建 Pull Request
        </div>
        <div style="display: flex;justify-content: space-between;align-items: center;width: 850px;padding-top: 10px">
          <div class="branch-wrapper" style="display: block">
            <div style="display: flex;justify-content: start;padding-top: 10px;padding-bottom: 10px">源分支</div>
            <div class="branchBox">
              <div class="repoNameBox" >
                {{ sourceRepo.repoName }}
              </div>
              <div>
                <el-select  v-model="sourceBranch" placeholder="Select">
                  <el-option
                      v-for="item in sourceBranchList" @click="setSourceBranch(item)"
                  >
                    {{item.branchName}}
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
          <div style="margin-left: -10px;display: flex;margin-top: 37px">
            <el-icon color="#8c92a4" size="20px">
              <ArrowRightBold />
            </el-icon>
          </div>
          <div class="branch-wrapper" style="display: block">
            <div style="display: flex;justify-content: start;padding-top: 10px;padding-bottom: 10px">目标分支</div>
            <div class="branchBox">
              <div>
                <div>
                  <el-dropdown >
                    <div>
                      <el-input
                          v-model="fuckinghell"
                          class="w-50 m-2"
                          placeholder="目标仓库"
                          @input="repoload"
                      />
                    </div>
                    <template #dropdown >
                      <el-dropdown-menu>
                        <div v-if="repoTotal>0"  v-for="item in repoList" style="display: block;width: 150px" >
                          <el-dropdown-item @click="setSearch(item)">{{item.repoName}}</el-dropdown-item>
                        </div>
                        <div v-else>
                          <el-dropdown-item >请输入仓库</el-dropdown-item>
                        </div>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
              <div>
                <el-select v-model="targetBranch"  placeholder="Select" >
                  <el-option
                      v-for="item in targetBranchList"  @click="setTargetBranch(item)"
                  >
                    {{item.branchName}}
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="same===true">
        <div class="warningBox" >
          请选择不同的分支
        </div>
      </div>
      <div v-else>
        <div class="successBox" >
          可以合并
        </div>
        <div class="HeaderInput">
          <el-input v-model="title" placeholder="标题" />
        </div>
        <div class="editor">
          <div style="border: 1px solid #ccc; margin-top: 10px">
            <Toolbar
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
                style="border-bottom: 1px solid #ccc"
            />
            <Editor
                :defaultConfig="editorConfig"
                :mode="mode"
                v-model="valueHtml"
                style="height: 300px; overflow-y: hidden"
                @onCreated="handleCreated"
            />
          </div>
        </div>
        <div class="confirm" style="display: flex;justify-content: center">
          <el-button @click="createPull">确认</el-button>
          <el-button @click="canclePull">取消</el-button>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import '@wangeditor/editor/dist/css/style.css';
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import {ArrowRightBold} from "@element-plus/icons-vue";
import request from "@/utils/request";
export default {
  components: {
    Editor,
    Toolbar,
    ArrowRightBold
  },
  setup() {
    // 编辑器实例，必须用 shallowRef，重要！
    const editorRef = shallowRef();
    // 内容 HTML
    const valueHtml = ref('<p>hello</p>');
    // 模拟 ajax 异步获取内容
    onMounted(() => {
      setTimeout(() => {
        valueHtml.value = '<p>请输入内容</p>';
      }, 1500);
    });
    const toolbarConfig = {};
    const editorConfig = { placeholder: '请输入内容...' };
    // 组件销毁时，也及时销毁编辑器，重要！
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });
    // 编辑器回调函数
    const handleCreated = (editor) => {
      console.log('created', editor);
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    const customPaste = (editor, event, callback) => {
      console.log('ClipboardEvent 粘贴事件对象', event);
      // 自定义插入内容
      editor.insertText('xxx');

      // 返回值（注意，vue 事件的返回值，不能用 return）
      callback(false); // 返回 false ，阻止默认粘贴行为
      // callback(true) // 返回 true ，继续默认的粘贴行为
    };

    const printHtml = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      return editor.getHtml();
    };

    const disable = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.disable()
    };

    return {
      editorRef,
      mode: 'default',
      valueHtml,
      toolbarConfig,
      editorConfig,
      handleCreated,
      customPaste,
      printHtml,
      disable,
    };
  },
  created(){
    request.post("/repo/info",  {"ownerId":this.$route.params.userName, "repoName":this.$route.params.repoName}).then(res => {
      console.log(res)
      this.sourceRepo=res.data
    })
    this.userId=sessionStorage.getItem("userId")
    this.load()
  },
  update(){
    this.load()
  },
  methods:{
    setTargetBranch(item){
      this.targetBranch=item.branchName;
      console.log("!!!")
      console.log(this.sourceBranch)
      console.log(this.targetBranch)
      console.log(this.sourceRepo)
      console.log(this.targetRepoName)
      console.log("!!!")
      if((this.sourceBranch===this.targetBranch)&&(this.sourceRepo===this.targetRepoName)){
        this.same=true;
      }
      else {
        this.same=false
      }
      console.log(this.same)
    },
    setSourceBranch(item){
      this.sourceBranch=item.branchName;
      console.log("!!!")
      console.log(this.sourceBranch)
      console.log(this.targetBranch)
      console.log(this.sourceRepo)
      console.log(this.targetRepoName)
      console.log("!!!")
      if((this.sourceBranch===this.targetBranch)&&(this.sourceRepo===this.targetRepoName)){
        this.same=true;
      }
      else {
        this.same=false
      }
      console.log(this.same)
    },
    load(){
      console.log("!!!")
      console.log(this.sourceBranch)
      console.log(this.targetBranch)
      console.log(this.sourceRepo)
      console.log(this.targetRepoName)
      console.log("!!!")
      if((this.sourceBranch===this.targetBranch)&&(this.sourceRepo===this.targetRepoName)){
        this.same=true;
      }
      else {
        this.same=false
      }
      console.log(this.same)
      request.get('/'+this.$route.params.userName+'/'+this.$route.params.repoName+'/branches').then(res => {
        console.log(res)
        this.sourceBranchList = res.data
      })
      request.get('/'+this.targetRepo.ownerName+'/'+this.targetRepo.repoName+'/branches').then(res => {
        console.log(res)
        this. targetBranchList = res.data
      })
    },
    repoload(){
      if(this.search===''){
        this.search=null
        this.RepoTota=0
        return
      }
      request.get("/repo/search", {
        params:{
          currentPage: 1,
          pageSize: 10,
          search:this.fuckinghell
        }
      }).then(res => {
        console.log(res)
        this.repoList=res.data.records
        this.repoTotal=res.data.total
      })
    },
    setSearch(item){
      console.log(item)
      this.targetRepo=item
      this.targetRepoName=item.repoName
      console.log(this.targetRepo)
      this.fuckinghell=item.repoName
      this.load()
    },
    createPull(){
      if(this.title==null){
        this.$notify({
          title: '错误',
          message: '标题不可为空',
          type: 'error',}
        )
        return
      }
      this.content=this.printHtml()
      console.log(this.content)
      request.post("/repo/create_pulls",  {"prTitle":this.fuckinghell,"prContent":this.printHtml(),"sourceRepoId":this.sourceRepo.repoId,"targetRepoId":this.targetRepo.repoId,"sourceBranch":this.sourceBranch,"targetBranch":this.targetBranch,"userId":this.userId,"mergerId":sessionStorage.getItem("userId")}).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: 'PR创建成功',
            type: 'success',
          })
          this.$router.push("../")
        }
        else {
          this.$notify({
            title: '错误',
            message: res.msg,
            type: 'error',
          })
        }
      })
    },
    canclePull(){
      this.$router.push("../")
    },
    },
  data(){
    return{
      fuckinghell:'',
      userId:'',
      sourceBranchList:[],
      targetBranchList:[],
      sourceRepo:'',
      targetRepo:'',
      sourceBranch:'',
      targetBranch:'',
      repoList:'',
      repoTotal:'',
      targetRepoName:'',
      same:true,
      title:'',
    }
  }
};
</script>

<style>
.main-body{
  width: 1000px;
}
.repoNameBox{
  display:flex;
  border:1px solid #dce3e8;
  align-items: center;
  justify-content: center;
  background: #f0f4f6;
  padding-left: 5px;
  padding-right: 5px;
  min-width: 150px;
}
.branchBox{
  display: flex;
  justify-content: start;
  max-height: 35px;
}
.branch-wrapper{
  width: 390px;
}
.warningBox{
  height: 45px;
  border-radius: 3px;
  background-color: #ffe8e6;
  color: #DB2828;
  box-shadow: 0px 0px 0px 1px #db2828 inset, 0px 0px 0px 0px rgb(0 0 0 / 0%);
  display: flex;
  align-items: center;
  padding-left:20px ;
}
.successBox{
  height: 45px;
  border-radius: 3px;
  background-color: #effff1;
  color: #39B54A;
  border: 1px solid #39B54A;
  display: flex;
  align-items: center;
  padding-left:20px ;
}
</style>

